<template>
  <page-wrap :show-top="false" :bgColor="topBg" :dark="false" class="pageWrap">
    <view class="page-container">
      <!-- 全局加载动画 -->
      <view class="top_bar">
        <view class="top_tabs_bar">
          <view class="hp-filter-wrap">
            <view :class="['hp-filter', { fixed: filterFixed }]">
              <view class="filter-post">
                <view class="post-list">
                  <text
                    :class="['post-item', { active: activeAim == index }]"
                    v-for="(item, index) in aimList"
                    :key="index"
                    @click="handleTopTabClick(index)"
                    >{{ item.label }}</text
                  >
                </view>
              </view>
            </view>
          </view>
        </view>

        <view class="search_bar">
          <view class="search">
            <u-search
              placeholder="请输入关键词"
              class="library-u-search"
              v-model="keyword"
              height="80"
              bg-color="white;"
              border-color="#BBBBBB"
              @search="handleSearch($event, 'enter')"
              maxlength="20"
              :show-action="false"
            ></u-search>
          </view>
        </view>
        <view @click="showAreaPopup = true" class="filter-btn"> 筛选 </view>
      </view>
      <view class="positionList">
        <EnterprisesItem
          v-for="item in infoItemsList"
          :key="item.id"
          :item="item"
          :props="infoItemprops"
          @itemClick="handleItemClick"
        />
      </view>
      <!-- <view class="text-bottom-tips">{{ text_bottom_tips }}</view> -->
      <u-empty
        class="empty-layout"
        v-if="showEmpty"
        text="暂无数据"
        mode="list"
      ></u-empty>
    </view>
    <u-loadmore
      v-if="infoItemsList.length > 0"
      :status="status"
      :load-text="loadText"
      font-size="24"
      color="#bfbfbf"
    />
    <view
      v-if="status == 'nomore' && infoItemsList.length > 0"
      class="text-bottom-tips"
      >{{ text_bottom_tips }}</view
    >

    <view class="loading-mask" v-if="loading && !isMore">
      <u-loading mode="circle" size="50" color="#F04646"></u-loading>
      <text class="loading-text">加载中...</text>
    </view>
    <LoginDialog
      ref="loginDialog"
      @loginSuccessBack="loginSuccessBack"
    ></LoginDialog>
    <!-- 区域筛选弹窗 -->
    <u-popup
      v-model="showAreaPopup"
      mode="bottom"
      :height="720"
      @close="onPopupClose"
      safe-area-inset-bottom
    >
      <AreaFilter
        :cityList="cityList"
        ref="areaFilterRef"
        @confirm="handleAreaConfirm"
        @cancel="showAreaPopup = false"
      />
    </u-popup>
    <!-- <u-loadmore v-else class="position-more" :status="status" :load-text="loadText" /> -->
    <!-- <u-loading-page :loading="loading"></u-loading-page> -->
  </page-wrap>
</template>

<script>
import ShareMixin from "@/mixins/share";
import loginOutMixin from "@/mixins/login-out.js";
import loginMixin from "@/mixins/login.js";
import LoginDialog from "@/components/LoginDialog";
import AreaFilter from "./components/AreaFilter.vue";
import EnterprisesItem from "./components/EnterprisesItem.vue";
import {
  getHomeJobList,
  getEnterpriseRegionList,
} from "@/api/modules/enterprises";

export default {
  components: {
    LoginDialog,
    EnterprisesItem,
    AreaFilter,
  },

  mixins: [ShareMixin, loginOutMixin, loginMixin],
  data() {
    return {
      navHeight: getApp().globalData.navHeight + uni.upx2px(0),
      filterFixed: false,
      text_bottom_tips:
        "岗位信息来源网络，由平台AI整理发布，招聘详细信息请以官网为准，如有问题请及时联系我们，邮箱pm@job1001.com，400-884-1001",

      searchIcon: this.$imgBaseSelf + "common/search.png",
      iconArrowDown: this.$imgBaseSelf + "enterprises/arrow_down.png",
      iconSort: this.$imgBaseSelf + "enterprises/icon_sort.png",

      keyword: "",
      searchResultList: [],

      activeAim: 0,
      aimList: [
        {
          label: "社招",
          idx: 0,
        },
        {
          label: "校招",
          idx: 1,
        },
      ],

      switchIndex: 0,
      switchList: ["最相关", "最新"],

      infoItemsList: [],
      infoItemprops: {
        title: "oriPositionName",
        summaryPositionDemand: "summaryPositionDemand",
        summarySkillsRequired: "summarySkillsRequired",
        site: "workPlace",
        companyInfo: "company",
        companyName: "shortName", // company.shortName
        name: "name",
        jobType: "jobType",
        pic: "logoUrl", // company.logoUrl
        date: "publishTime",
        id: "id",
      },

      advItems: [],

      uNavColor: this.$uNavColor,
      showTop: false,
      personId: uni.getStorageSync("person-id").slice(2) || undefined,
      sharePath: "/pages/enterprises/index",
      isLogin: false,
      loading: false,
      page: 1,
      size: 10,
      total: 0,
      isMore: false,
      showEmpty: false,
      status: "loading",
      loadText: {
        loadmore: "加载更多",
        loading: "加载中",
        nomore: "没有更多了",
      },
      showAreaPopup: false,
      // 城市区域数据，实际项目中可从接口获取
      cityList: [],
      selectedAreaIds: [], // 用于记录已选中的区域ID，方便回显
    };
  },

  created() {
    this.navHeight = getApp().globalData.navHeight;
    this.getJobsList(false);
    this.getEnterpriseRegionList();
  },

  onShow() {
    this.personId = uni.getStorageSync("person-id").slice(2) || undefined;
  },

  onPageScroll(res) {
    this.showTop = res.scrollTop > 0;
  },
  onReachBottom() {
    console.log("onReachBottom:", this.page);
    if (this.status != "nomore") {
      this.page += 1;
      this.getJobsList(true);
    }
  },

  methods: {
    // tab切换
    handleTopTabClick(index) {
      this.activeAim = index;
      this.page = 1;
      this.infoItemsList = [];
      this.selectedAreaIds = [];
      // 调用AreaFilter组件的重置方法
      if (this.$refs.areaFilterRef) {
        this.$refs.areaFilterRef.resetSelection();
      }
      this.status = "loading";
      this.getJobsList(false);
      this.getEnterpriseRegionList();
    },

    handleItemClick(item) {
      uni.navigateTo({
        url:
          "/pagesSub/enterprises/detail/index?jobId=" +
          item.id +
          "&oriPositionName=" +
          item.oriPositionName,
      });
    },

    // 获取列表数据
    getJobsList(isMore) {
      this.isMore = isMore;
      if ((isMore && this.loading) || this.status == "nomore") return;
      this.loading = true;
      // if (this.status == "loading") return;
      this.status = "loading";
      let param = {
        personId: this.personId,
        pageNo: this.page,
        pageSize: this.size,
        workCifyList: this.selectedAreaIds,
        name: this.keyword,
        recruitType: this.activeAim == 0 ? 2 : 1, // 招聘类型:1=校招，2=社招
      };
      getHomeJobList(param)
        .then((res) => {
          if (res.code !== 200) {
            this.status = "nomore";
            this.infoItemsList = [];
            this.showEmpty = true;
            uni.showToast({ icon: "none", title: "获取数据失败" });
          } else {
            if (isMore) {
              this.infoItemsList.push(...(res.data || []));
            } else {
              this.infoItemsList = res.data || [];
            }
            this.showEmpty = this.infoItemsList.length == 0;
            if (res.data) {
              this.status = "loadmore";
              if (this.infoItemsList.length >= res.pageparam.sums) {
                this.status = "nomore";
              }
            } else {
              this.status = "nomore";
            }
          }
          this.loading = false;
        })
        .catch((err) => {
          this.loading = false;
        });
    },

    getEnterpriseRegionList() {
      let param = {
        recruitType: this.activeAim == 0 ? 2 : 1, // 招聘类型:1=校招，2=社招
      };
      getEnterpriseRegionList(param).then((res) => {
        if (res.code == 200) {
          if (res.data) {
            this.cityList = res.data;
          }
        }
      });
    },

    ////////////////////////////////////////////////////////////////////////////////////////////
    //////////////////////////////begin --搜索--//////////////////////////////////////////////////

    handleSearch(e, tag) {
      console.log("handleSearch:", e, tag);
      this.status = "loading";
      this.keyword = e;
      this.page = 1;
      this.getJobsList(false);
      // 新增：滚动回顶部
      uni.pageScrollTo({
        scrollTop: 0,
        duration: 300,
      });
    },

    // 处理信息项点击
    handleMessageRoute(item) {
      if (!this.personId) {
        this.showLoginDialog();
        return;
      }

      uni.navigateTo({
        url: item.path,
      });
    },

    // 处理功能项点击
    handleMainFuncRoute(item) {
      if (!this.personId) {
        this.showLoginDialog();
        return;
      }

      if (item.isTab) {
        uni.switchTab({
          url: item.path,
        });
      } else {
        uni.navigateTo({
          url: item.path,
        });
      }
    },

    handleReflesh() {
      let param = {
        person_id: this.personId,
      };
      refreshResume(param).then((res) => {
        if (res && +res.code == 200) {
          uni.showToast({ icon: "none", title: "刷新成功" });
        }
      });
    },

    refreshInfo() {
      let tabBarList =
        getApp().globalData.loginStatus == "company"
          ? getApp().globalData.companyTabs
          : getApp().globalData.personTabs;
      getApp().globalData.tabBarList = tabBarList;
    },

    // 处理区域筛选确认
    handleAreaConfirm(selectedAreas) {
      console.log("handleAreaConfirm:", selectedAreas);
      this.showAreaPopup = false;
      // 保存选中的区域ID，用于后续回显
      if (selectedAreas) {
        this.selectedAreaIds = selectedAreas.map((item) => item.provinceid);
      }
      this.handleSearch();
    },
    // 关闭弹窗时的处理
    onPopupClose() {
      this.showAreaPopup = false;
    },
    // ===BEGIN==== 登录相关 ======
    // ========

    // 显示登录对话框
    showLoginDialog() {
      this.$refs.loginDialog.setVisibility(true);
    },
    // 退出登录
    handleLogOut() {
      this.loginOut(null, () => {
        this.personId = "";
      });
    },
    // 登录成功回调
    loginSuccessBack() {
      this.personId = uni.getStorageSync("person-id").slice(2) || undefined;
      if (this.personId && !this.isLogin) {
        this.refreshInfo();
        this.isLogin = true;
        // getApp().watch((val) => {
        //   this.kingKongList[0].cnt = val;
        // }, 'meCount');
        this.$bus.$on("updatePersonDetail", this.getPersonDetail);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
$img-base-mine: $img-base + "mine/";
@include img-base-self(".person-top", "pcenter/bg.png?v=1");
@keyframes loading {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}
::v-deep .u-close--top-right {
  top: 5rpx !important;
  right: 5rpx !important;
}

.page-container {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  // background: url($img-base-mine + 'minebg.png') no-repeat top / 100% 30% #f5f5f5;

  .top_bar {
    background: url($img-base-mine + "minebg.png");
    background-size: cover;
    position: fixed;
    height: 338rpx;
    width: 100%;
    z-index: 10000;
    // 头部导航栏
    .top_tabs_bar {
      position: relative;
      margin-top: 78rpx;
      z-index: 100;

      .hp-filter-wrap {
        .hp-filter {
          &.fixed {
            position: fixed;
            left: 0;
            top: 0;
            z-index: 10;
            width: 100%;
            background: $uni-bg-color-grey;
          }

          .filter-post {
            display: flex;
            align-items: center;
            padding: 16rpx 32rpx 14rpx 32rpx;
            // margin-bottom: $uni-spacing-col-lg;
            // background-color: #fff;

            .post-list {
              flex-grow: 1;
              display: flex;
              align-items: center;
              overflow: auto;

              .post-item {
                margin-left: 16rpx;
                padding: 16rpx;
                font-size: 32rpx;
                white-space: nowrap;

                &:first-of-type {
                  margin-left: 0;
                }

                &.active {
                  position: relative;
                  font-size: 34rpx;
                  font-weight: bold;

                  // color: #ffffff;
                  // background: $search-bg;
                  // border-radius: 33rpx;
                  &::after {
                    display: inline-block;
                    position: absolute;
                    bottom: 0;
                    left: 50%;
                    transform: translateX(-50%);
                    content: "";
                    width: 56rpx;
                    height: 14rpx;
                    background-image: url($img-base + "select.png");
                    background-repeat: no-repeat;
                    background-size: 100% 100%;
                  }
                }
              }
            }
          }
        }
      }
    }

    // 搜索栏
    .search_bar {
      position: relative;
      display: flex;
      flex-direction: column;
      align-items: center;
      height: 84rpx;
      margin-top: 7rpx;
      .search {
        display: flex;
        // padding: 28rpx 32rpx;
        border-radius: 36rpx;

        ::v-deep.u-content {
          padding: 0 20rpx 0rpx 32rpx;
        }

        ::v-deep.u-close-wrap {
          transform: scale(1.3);
        }

        .library-u-search {
          flex: 1;
          width: 686rpx;
          height: 72rpx;
        }
      }

      .searchResult {
        width: 100%;
        background-color: #fff;
        bottom: -120rpx;
        height: calc(100vh - 260rpx);
        overflow: scroll;

        .resultList {
          overflow: scroll;
          padding-bottom: 48rpx;

          .resultItem {
            padding: 36rpx 32rpx;
            border-bottom: 1rpx solid #f5f5f5;

            &:last-of-type {
              border-bottom: 0;
            }

            .resultTitle {
              font-size: 30rpx;
              font-family: PingFangSC-Regular, PingFang SC;
              font-weight: 400;
              line-height: 40rpx;
              margin-bottom: 16rpx;

              .light {
                color: #f75a3e;
              }
            }

            .resultDesc {
              font-size: 26rpx;
              font-family: PingFangSC-Regular, PingFang SC;
              font-weight: 400;
              color: #888888;
              line-height: 40rpx;
            }
          }
        }
      }

      .noneResult {
        display: flex;
        flex-direction: column;
        align-items: center;
        width: 100%;
        border-radius: 8rpx;
        font-size: 28rpx;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        margin-top: 130rpx;

        .empty_image {
          width: 400rpx;
          height: 400rpx;
        }

        .empty-title {
          color: #bfbfbf;
          line-height: 40rpx;
        }
      }
    }
  }

  .filter-btn {
    font-family: MiSans, MiSans;
    font-weight: 400;
    font-size: 24rpx;
    color: #555555;
    line-height: 24rpx;
    padding: 24rpx 40rpx;
    width: 130rpx;
  }

  .positionList {
    margin-top: 330rpx;
  }
  .empty-layout {
    position: absolute;
    top: 140rpx;
    left: 0;
    bottom: 0;
    right: 0;
  }
}
// 底部提示文字
.text-bottom-tips {
  font-family: MiSans, MiSans;
  font-weight: 400;
  font-size: 22rpx;
  color: #888888;
  line-height: 34rpx;
  text-align: left;
  padding: 34rpx;
}
.loading-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: #ffffff;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}
.loading-text {
  margin-top: 20rpx;
  color: #666;
}

.person-top {
  height: 100rpx;
  background-repeat: no-repeat;
  background-position: center bottom;
  background-size: 100% 100%;
  border-radius: 0 0 68rpx 68rpx;
}
</style>
